package com.geega.geetest.util;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author hao.yu8
 * @description 获取IP工具类
 */
public class IpUtil {
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        boolean unknownFlag = "unknown".equalsIgnoreCase(ip);
        if ((ip != null) && (ip.length() > 0) && ip.indexOf(",") > -1) {
            ip = ip.split(",")[0];
        }
        if ((ip == null) || (ip.length() == 0) || unknownFlag) {
            ip = request.getHeader("x-real-ip");
        }
        if ((ip == null) || (ip.length() == 0) || unknownFlag) {
            ip = request.getHeader("proxy-client-ip");
        }
        if ((ip == null) || (ip.length() == 0) || unknownFlag) {
            ip = request.getHeader("wl-proxy-client-ip");
        }
        if ((ip == null) || (ip.length() == 0) || unknownFlag) {
            ip = request.getRemoteAddr();
        }
        if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
            // 根据网卡取本机配置的IP
            InetAddress inet;
            try {
                inet = InetAddress.getLocalHost();
                ip = inet.getHostAddress();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
        }
        return ip;
    }

}
